/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  Modal,
  Alert,
  Select,
  Divider,
  Input,
  Typography,
  Space,
  Form,
  Radio,
  Tabs,
  message,
} from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { getMonitorConfig } from '@/services/operatorManagement';
import { noop } from 'lodash';

const { TabPane } = Tabs;

const getMonitorConfigs = async () => {
  const { data: receiveConfig } = await getMonitorConfig({ type: 'receive' });
  const { data: collectConfig } = await getMonitorConfig({ type: 'collect' });
  return {
    receiveConfig: { ...receiveConfig, type: 'receive' },
    collectConfig: { ...collectConfig, type: 'collect' },
  };
};
const formatBrands = (brands: string[]) => {
  return brands.join(',');
};

const monitorTypes = [
  { label: '超时接单时效', value: 'receive', flag: '接单' },
  { label: '超时揽收时效', value: 'collect', flag: '揽收' },
];

const monitorConfig = {
  receive: {
    options: [{ value: 1, label: '下单后一小时' }],
    alert: '注意：指用户下单超过设置范围时间后视为超时未接单',
    placeholder: '选择下单超时时间',
  },
  collect: {
    options: [{ value: 1.5, label: '接单后一个半小时' }],
    alert: `注意：指订单接单超过设置范围时间后视为超时未揽收`,
    placeholder: '选择揽收超时时间',
  },
};

let timer = '';

const { Option } = Select;

const Index: React.FC<{
  isOpened: boolean | undefined;
  onCancel: Function;
  onOk: Function;
  brandPromise: Promise<any>;
}> = (props) => {
  const { isOpened, onCancel, onOk, brandPromise } = props;
  const [monitorType, setMonitorType] = useState('receive');
  const typeRef = useRef({ type: 'receive' });
  const [options, setOptions] = useState(monitorConfig[monitorType].options);
  const [addHour, setAddHour] = useState();
  const [brandOptions, setBrandOptions] = useState([]);
  const [brandLoading, setBrandLoading] = useState(true);
  const [receiveForm] = Form.useForm();
  const [collectForm] = Form.useForm();

  const forms = {
    receive: receiveForm,
    collect: collectForm,
  };
  const setMonitorTypeGather = (type: string) => {
    setMonitorType(type);
    typeRef.current.type = type;
  };
  const addHourItem = useCallback(
    (params) => {
      const {
        type = monitorType,
        upVal = addHour,
        update = true,
        callback = noop,
        showTip = true,
      } = params;
      const has = monitorConfig[type].options.find((item: any) => {
        const { value } = item;
        return upVal == value;
      });
      let tip = '';
      if (!upVal) {
        tip = '请输入超时时间';
      }
      if (has) {
        tip = '选项已存在';
      }
      if (tip) {
        if (showTip) {
          message.warn(tip);
        }
        return;
      }
      monitorConfig[type].options = [
        ...monitorConfig[type].options,
        { value: upVal, label: `${type === 'receive' ? '下' : '接'}单后${upVal}小时` },
      ];
      if (update) {
        setOptions([...monitorConfig[type].options]);
      }
      callback();
    },
    [addHour, monitorType, options],
  );
  useEffect(() => {
    brandPromise.then((brands) => {
      setBrandOptions(brands);
      setBrandLoading(false);
    });
  }, []);

  useEffect(() => {
    getMonitorConfigs().then((res) => {
      const { type } = typeRef.current;
      Object.keys(res).forEach((key) => {
        const { brand, hour, type: itemType } = res[key];
        addHourItem({
          type: itemType,
          upVal: hour,
          update: itemType === type,
          showTip: false,
        });
        forms[itemType].setFieldsValue({
          [`${itemType}_brand`]: brand,
          [`${itemType}_hour`]: hour.toString(),
        });
      });
    });
  }, [timer, typeRef]);

  const handleMonitorTypeChange = (e: any) => {
    setMonitorTypeGather(e.target.value);
  };
  const handleOk = () => {
    Promise.allSettled([receiveForm.validateFields(), collectForm.validateFields()]).then(
      (results) => {
        let values = {};
        const error: any[] = [];
        results.forEach((item) => {
          if (item.status === 'fulfilled') {
            values = { ...values, ...item.value };
          } else {
            const { errorFields } = item.reason;
            error.push(errorFields);
          }
        });
        if (Object.keys(values).length === 0) {
          const [errorFields] = error || {};
          if (errorFields) {
            message.warning(errorFields?.[0]?.errors?.[0]);
          }
        } else {
          timer = new Date().getTime().toString();
          Object.keys(values).forEach((key) => {
            if (key.includes('brand')) {
              values[key] = formatBrands(values[key]);
            }
          });
          onOk(values);
        }
      },
    );
    try {
    } catch (errorInfo) {
      const { errorFields } = errorInfo || {};
      if (errorFields) {
        message.warning(errorFields?.[0]?.errors?.[0]);
      }
    }
  };
  const handleCancel = () => {
    onCancel();
  };

  const handleAddHourItem = () => {
    addHourItem({});
  };
  const onHourInputChange = (e: any) => {
    setAddHour(e.target.value);
  };
  const { alert, placeholder } = useMemo(() => {
    const { alert: tip, options: opt, placeholder: plhde } = monitorConfig[monitorType];
    setOptions(opt);
    return { alert: tip, placeholder: plhde };
  }, [monitorType]);

  return (
    <Modal visible={isOpened} onCancel={handleCancel} onOk={handleOk}>
      <Radio.Group
        onChange={handleMonitorTypeChange}
        optionType='button'
        value={monitorType}
        options={monitorTypes}
      />
      <Tabs activeKey={monitorType}>
        {monitorTypes.map((item) => {
          const { value, flag } = item;
          return (
            <TabPane key={value} forceRender={true}>
              <Form form={forms[value]}>
                <Alert message={alert} type='warning' closable></Alert>
                <Form.Item
                  name={`${value}_hour`}
                  label='超时时间'
                  style={{ marginTop: 10 }}
                  rules={[
                    {
                      required: true,
                      message: `请选择${flag}超时时间`,
                    },
                  ]}
                >
                  <Select
                    style={{ width: 300 }}
                    placeholder={placeholder}
                    dropdownRender={(menu) => (
                      <>
                        {menu}
                        <Divider style={{ margin: '8px 0' }} />
                        <Space align='center' style={{ padding: '0 8px 4px' }}>
                          <Input
                            placeholder='自定义小时'
                            type='number'
                            value={addHour}
                            onChange={onHourInputChange}
                          />
                          <Typography.Link
                            onClick={handleAddHourItem.bind(null)}
                            style={{ whiteSpace: 'nowrap' }}
                          >
                            <PlusOutlined /> 自定义小时
                          </Typography.Link>
                        </Space>
                      </>
                    )}
                  >
                    {options.map((iitem: any) => {
                      const { value: val, label } = iitem;
                      return <Option key={val}>{label}</Option>;
                    })}
                  </Select>
                </Form.Item>
                <Form.Item
                  name={`${value}_brand`}
                  label='针对品牌'
                  rules={[
                    {
                      required: true,
                      message: `请选择${flag}针对品牌`,
                    },
                  ]}
                >
                  <Select
                    mode='multiple'
                    placeholder='选择针对品牌'
                    style={{ width: 300 }}
                    loading={brandLoading}
                  >
                    {brandOptions.map((iitem: any) => {
                      const { value: val, label } = iitem;
                      return <Option key={val}>{label}</Option>;
                    })}
                  </Select>
                </Form.Item>
              </Form>
            </TabPane>
          );
        })}
      </Tabs>
    </Modal>
  );
};

export default Index;
